package com.admission.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.dom4j.Document;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ServletContextAware;
import org.springside.modules.orm.Page;
import org.xml.sax.SAXException;

import com.admission.dao.ProvinceScoreDao;
import com.admission.dao.RecruitmentDetailDao;
import com.admission.model.ProvinceScore;
import com.admission.model.RecruitmentDetail;
import com.admission.to.MainXml;
import com.admission.to.Province;
import com.admission.to.Type;
import com.admission.to.Year;
import com.usercalls.BeanToXmlAnaly;
import com.utils.XmlCreateUtil;

/**
 * 用于生成静态页面方法 录取统计
 * 
 */
@Repository
@Transactional
public class StaticRecruitment implements ServletContextAware {
	private final String RECRUITMENTDETAILHTML = "recruitment-detail.html";
	private final String RECRUITMENTDETAILHTMLLIST = "recruitment-detail-entry.html";
	// 用于详细信息页面的
	public static final String REPLACESTRING = "<tr class='admission-table-bg'><td>###sequence###</td><td>###academy###</td><td>###major###</td><td>###enroll###</td><td class='science'>###high###</td><td class='science'>###avg###</td><td  class='science' >###low###</td><td class='art'>###lowScoreSubject###</td><td class='art'>###lowScoreCulture###</td><td>###content###</td></tr>";
	public static final String PAGESTRING = "<a href='###pageurl###'>###pagenum###</a>";
	public static final String PREPAGESTRING = "<a href='###pageurl###'>上一页</a>";
	public static final String NEXTPAGESTRING = "<a href='###pageurl###'>下一页</a>";
	public static final String NEXT10PAGESTRING = "<a href='###pageurl###'>后十页</a>";
	public static final String PRE10PAGESTRING = "<a href='###pageurl###'>前十页</a>";
	// 一下语句用于标题列表页面的参数
	public static final String RECRUITMENTLINE = "<li><span class='arrow'></span><a href='###detailurl###'>###title###</a><span class='list-time'>###date###</span></li>";

	// select option
	public static final String SELECTYEAR = "<option value ='###key###'>###value###</option>";
	public static final String SELECTPROVINCE = "<option value ='###key###'>###value###</option>";
	public static final String SELECTTYPE = "<option value ='###key###'>###value###</option>";

	private ServletContext servletContext;
	private RecruitmentDetailDao recruitmentDetailDao;
	private ArrayUtils arrayUtils;
	private ProvinceScoreDao provinceScoreDao;

	public void createHtmlForRecruitmentDetail() throws IOException,
			IllegalArgumentException, SAXException, IllegalAccessException {
		setServletContext(servletContext);
		Map<String, String> provincesmap = arrayUtils.getProvinceMap();
		Map<String, String> typemap = arrayUtils.getType();
		List<String> years = recruitmentDetailDao
				.find("select distinct rd.year from RecruitmentDetail rd order by rd.year desc");

		List<String> provinces = recruitmentDetailDao
				.find("select distinct rd.province from RecruitmentDetail rd");
		List<String> types = recruitmentDetailDao
				.find("select distinct rd.type from RecruitmentDetail rd");
		String yearstr = "";
		String provincestr = "";
		String typestr = "";

		for (int i = 0; i < years.size(); i++) {
			yearstr += SELECTYEAR.replaceAll("###key###", years.get(i))
					.replaceAll("###value###", years.get(i));

		}

		for (int i = 0; i < provinces.size(); i++) {
			provincestr += SELECTPROVINCE.replaceAll("###key###",
					provinces.get(i)).replaceAll("###value###",
					provincesmap.get(provinces.get(i)));
		}

		for (int i = 0; i < types.size(); i++) {
			typestr += SELECTTYPE.replaceAll("###key###", types.get(i))
					.replaceAll("###value###", typemap.get(types.get(i)));
		}
		// 读取文档的时候，第一个字符无法读出，所以每行的第一个位置留空
		BufferedReader br = null;// 从字符输入流中读取文本，缓冲各个字符，从而实现字符、数组和行的高效读取
		br = new BufferedReader(new InputStreamReader(new FileInputStream(
				new File(servletContext.getRealPath("/") + "pages/masterplate/"
						+ RECRUITMENTDETAILHTML)), "UTF-8"));// 从文件系统中的某个文件中获得输入字节
		String strs = null;
		StringBuffer sbf = new StringBuffer();
		while (br.read() != -1) {// 读取单个字符。
			sbf.append(br.readLine());// 读取一个文本行
			sbf.append("\n");// 换行
		}

		Page<RecruitmentDetail> page = new Page<RecruitmentDetail>(
				PageUtils.DEFAULT_PAGE_SIZE);

		List<RecruitmentDetail> lrd = recruitmentDetailDao
				.find("from RecruitmentDetail group by year,province,type");
		// 默认页面
		strs = sbf.toString();
		strs = strs.replaceAll("###recruitment_id###", "recruitment-detail");
		strs = strs.replaceAll("###selectyear###", yearstr);
		strs = strs.replaceAll("###selecttype###", typestr);
		strs = strs.replaceAll("###selectprovince###", provincestr);
		strs = strs.replaceAll("###area###", "")
				.replaceAll("###postdate###", "")
				.replaceAll("###inputby###", "")
				.replaceAll("###title###", "录取统计")
				.replaceAll("###firstLine###", "")
				.replaceAll("###secondLine###", "")
				.replaceAll("###toudangLine###", "");
		// 插入页码

		strs = strs.replaceAll("###pagenum###", "");

		File file1 = new File(servletContext.getRealPath("/")
				+ "/statichtml/recruitment-detail.html");
		if (!file1.exists()) {
			file1.getParentFile().mkdirs();
			file1.createNewFile();
		}
		FileOutputStream fos1 = new FileOutputStream(file1);
		OutputStreamWriter osw1 = new OutputStreamWriter(fos1, "UTF-8");
		PrintWriter outFile1 = new PrintWriter(osw1);
		outFile1.write(strs);// 写入
		osw1.close();
		fos1.close(); // 关闭资源

		long pageTotal = 1;

		for (int k = 0; k < lrd.size(); k++) {

			for (int j = 1; j <= pageTotal; j++) {
				strs = sbf.toString();
				strs = strs.replaceAll("###recruitment_id###",
						"recruitment-detail-" + lrd.get(k).getYear() + "-"
								+ lrd.get(k).getProvince() + "-"
								+ lrd.get(k).getType());
				List<String> l = recruitmentDetailDao
						.find("select sum(ed.enrollNum) from RecruitmentDetail ed where year='"
								+ lrd.get(k).getYear()
								+ "' and province='"
								+ lrd.get(k).getProvince()
								+ "' and type='"
								+ lrd.get(k).getType() + "'");

				String title = lrd.get(k).getYear() + "年"
						+ provincesmap.get(lrd.get(k).getProvince())
						+ typemap.get(lrd.get(k).getType()) + "录取情况统计";

				strs = strs.replaceAll("###selectyear###", yearstr);
				strs = strs.replaceAll("###selecttype###", typestr);
				strs = strs.replaceAll("###selectprovince###", provincestr);
				StringBuffer addstr = new StringBuffer();
				page.setPageNo(j);
				// Criterion criterions = Restrictions.eq("recruitment.id", id);
				Criterion criterions = Restrictions.eq("year", lrd.get(k)
						.getYear());
				Criterion criterions1 = Restrictions.eq("province", lrd.get(k)
						.getProvince());
				Criterion criterions2 = Restrictions.eq("type", lrd.get(k)
						.getType());
				List<ProvinceScore> ps = provinceScoreDao.find(criterions,
						criterions1, criterions2);
				page = recruitmentDetailDao.findPage(page, criterions,
						criterions1, criterions2);
				if (page.getTotalCount() <= 0) {
					break;
				}
				pageTotal = page.getTotalPages();
				List<RecruitmentDetail> rds = page.getResult();
				for (int i = 0; i < rds.size(); i++) {
					if (i == 0) {
						String t = REPLACESTRING
								.replaceAll("###academy###", "")
								.replaceAll("###major###", "录取总数")
								.replaceAll("###enroll###",
										l.get(0).equals("0") ? "" : l.get(0))
								.replaceAll("###high###", "")
								.replaceAll("###avg###", "")
								.replaceAll("###low###", "")
								.replaceAll("###lowScoreSubject###", "")
								.replaceAll("###lowScoreCulture###", "")
								.replaceAll("###sequence###", "")
								.replaceAll("###content###", "");
						addstr.append(t);
					}
					String t = REPLACESTRING
							.replaceAll("###academy###",
									rds.get(i).getAcademy())
							.replaceAll("###major###", rds.get(i).getMajor())
							.replaceAll("###enroll###",
									rds.get(i).getEnrollNum())
							.replaceAll("###high###",
									rds.get(i).getHightScore())
							.replaceAll("###avg###", rds.get(i).getAvgScore())
							.replaceAll("###low###", rds.get(i).getLowScore())
							.replaceAll("###lowScoreSubject###",
									rds.get(i).getLowScoreSubject())
							.replaceAll("###lowScoreCulture###",
									rds.get(i).getLowScoreCulture())
							.replaceAll(
									"###sequence###",
									String.valueOf(i + 1
											+ (page.getPageNo() - 1) * 20))
							.replaceAll("###content###",
									rds.get(i).getContent());
					if (i % 2 == 1) {
						t = t.replaceAll("admission-table-bg", "");
					}
					addstr.append(t);

				}
				strs = strs
						.replaceAll("###area###", addstr.toString())
						.replaceAll("###postdate###", rds.get(0).getInputTime())
						.replaceAll("###inputby###", rds.get(0).getInputBy())
						.replaceAll("###title###", title);
				// 插入分数线
				if (ps.size() > 0) {
					strs = strs
							.replaceAll("###firstLine###",
									ps.get(0).getFirstLine())
							.replaceAll("###secondLine###",
									ps.get(0).getSecondLine())
							.replaceAll("###toudangLine###",
									ps.get(0).getToudangLine());
				} else {
					strs = strs.replaceAll("###firstLine###", "")
							.replaceAll("###secondLine###", "")
							.replaceAll("###toudangLine###", "");
				}

				// 插入页码
				String pageString = "";
				for (int i = (j - 1) / 10 * 10 + 1; i <= page.getTotalPages()
						&& i < ((j - 1) / 10 + 1) * 10 + 1; i++) {
					pageString += PAGESTRING.replaceAll("###pagenum###",
							String.valueOf(i)).replaceAll(
							"###pageurl###",
							"./../statichtml/recruitment-detail-"
									+ lrd.get(k).getYear() + "-"
									+ lrd.get(k).getProvince() + "-"
									+ lrd.get(k).getType() + "-"
									+ String.valueOf(i) + ".html?year="
									+ lrd.get(k).getYear() + "&&province="
									+ lrd.get(k).getProvince() + "&&type="
									+ lrd.get(k).getType());
				}
				pageString += NEXTPAGESTRING.replaceAll(
						"###pageurl###",
						"./../statichtml/recruitment-detail-"
								+ lrd.get(k).getYear() + "-"
								+ lrd.get(k).getProvince() + "-"
								+ lrd.get(k).getType() + "-"
								+ String.valueOf(page.getNextPage())
								+ ".html?year=" + lrd.get(k).getYear()
								+ "&&province=" + lrd.get(k).getProvince()
								+ "&&type=" + lrd.get(k).getType());
				pageString = PREPAGESTRING.replaceAll(
						"###pageurl###",
						"./../statichtml/recruitment-detail-"
								+ lrd.get(k).getYear() + "-"
								+ lrd.get(k).getProvince() + "-"
								+ lrd.get(k).getType() + "-"
								+ String.valueOf(page.getPrePage())
								+ ".html?year=" + lrd.get(k).getYear()
								+ "&&province=" + lrd.get(k).getProvince()
								+ "&&type=" + lrd.get(k).getType())
						+ pageString;
				if ((j - 1) / 10 != 0) {
					pageString = PRE10PAGESTRING.replaceAll(
							"###pageurl###",
							"./../statichtml/recruitment-detail-"
									+ lrd.get(k).getYear() + "-"
									+ lrd.get(k).getProvince() + "-"
									+ lrd.get(k).getType() + "-"
									+ String.valueOf(j / 10 * 10)
									+ ".html?year=" + lrd.get(k).getYear()
									+ "&&province=" + lrd.get(k).getProvince()
									+ "&&type=" + lrd.get(k).getType())
							+ pageString;
				}
				if (((j - 1) / 10 + 1) * 10 < page.getTotalPages()) {
					pageString = pageString
							+ NEXT10PAGESTRING
									.replaceAll(
											"###pageurl###",
											"./../statichtml/recruitment-detail-"
													+ lrd.get(k).getYear()
													+ "-"
													+ lrd.get(k).getProvince()
													+ "-"
													+ lrd.get(k).getType()
													+ "-"
													+ String.valueOf(((j - 1) / 10 + 1) * 10 + 1)
													+ ".html?year="
													+ lrd.get(k).getYear()
													+ "&&province="
													+ lrd.get(k).getProvince()
													+ "&&type="
													+ lrd.get(k).getType());
				}
				pageString = pageString + "共" + (page.getTotalPages()) + "页";
				strs = strs.replaceAll("###pagenum###", pageString);

				File file = new File(servletContext.getRealPath("/")
						+ "/statichtml/recruitment-detail-"
						+ lrd.get(k).getYear() + "-" + lrd.get(k).getProvince()
						+ "-" + lrd.get(k).getType() + "-" + page.getPageNo()
						+ ".html");
				if (!file.exists()) {
					file.getParentFile().mkdirs();
					file.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(file);
				OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
				PrintWriter outFile = new PrintWriter(osw);
				outFile.write(strs);// 写入
				osw.close();
				fos.close(); // 关闭资源
			}
		}
		createSelectOption();
		createHtmlForRecruitmentDetailList();
	}

	public void createSelectOption() throws IllegalArgumentException,
			SAXException, IllegalAccessException, IOException {
		Map<String, String> provincesmap = arrayUtils.getProvinceMap();
		Map<String, String> typemap = arrayUtils.getType();
		List<String> years = recruitmentDetailDao
				.find("select distinct rd.year from RecruitmentDetail rd order by rd.year desc");
		MainXml ex = new MainXml();
		List<Year> eys = new ArrayList<Year>();

		for (int i = 0; i < years.size(); i++) {
			Year ey = new Year();
			ey.setName(years.get(i));

			List<String> provinces = recruitmentDetailDao
					.find("select distinct rd.province from RecruitmentDetail rd where rd.year='"
							+ years.get(i) + "' ");
			List<Province> eps = new ArrayList<Province>();
			for (int j = 0; j < provinces.size(); j++) {
				Province ep = new Province();
				ep.setKey(provinces.get(j));
				ep.setValue(provincesmap.get(provinces.get(j)));

				List<String> types = recruitmentDetailDao
						.find("select distinct rd.type from RecruitmentDetail rd where rd.year='"
								+ years.get(i)
								+ "' and rd.province='"
								+ provinces.get(j) + "'");
				List<Type> ets = new ArrayList<Type>();
				for (int k = 0; k < types.size(); k++) {
					Type et = new Type();
					et.setKey(types.get(k));
					et.setValue(typemap.get(types.get(k)));
					ets.add(et);
				}
				ep.setTypes(ets);
				eps.add(ep);
			}
			ey.setProvinces(eps);
			eys.add(ey);

		}
		ex.setYears(eys);

		BeanToXmlAnaly toXml = new BeanToXmlAnaly();
		toXml.setEncodeing("utf-8", "root");
		Document doc = toXml.beanToXmlDoc(ex, true);
		doc.setXMLEncoding("UTF-8");
		String path = FileUtils.getProjectRoot();
		path += "/WEB-INF/other/recruitment.xml";
		XmlCreateUtil.createXml(path, doc);
	}

	/**
	 * 列表静态化
	 * 
	 * @throws IOException
	 */
	public void createHtmlForRecruitmentDetailList() throws IOException {
		setServletContext(servletContext);
		Map<String, String> provincesmap = arrayUtils.getProvinceMap();
		Map<String, String> typemap = arrayUtils.getType();
		final String replaceLine = "<li><img src=\"../images/home_point3.png\" class=\"li-point\" /><a href=\"../base/recruitment-detail.action?year=###year###&province=###provincekey###&type=###typekey###\" class=\"addNew\">###year######provincevalue######typevalue###录取统计</a><span class=\"list-time\">###inputTime###</span></li>";
		BufferedReader br = null;// 从字符输入流中读取文本，缓冲各个字符，从而实现字符、数组和行的高效读取
		br = new BufferedReader(new InputStreamReader(new FileInputStream(
				new File(servletContext.getRealPath("/") + "pages/masterplate/"
						+ RECRUITMENTDETAILHTMLLIST)), "UTF-8"));// 从文件系统中的某个文件中获得输入字节
		String strs = null;
		StringBuffer sbf = new StringBuffer();
		while (br.read() != -1) {// 读取单个字符。
			sbf.append(br.readLine());// 读取一个文本行
			sbf.append("\n");// 换行
		}
		strs = sbf.toString();
		List<RecruitmentDetail> l = recruitmentDetailDao
				.find("from RecruitmentDetail group by year,province,type order by year desc ");
		String area = "";

		int i = 0;
		for (i = 0; i < l.size(); i++) {
			if (i > 0 && (i + 1) % PageUtils.DEFAULT_PAGE_SIZE == 0) {
				strs = strs
						.replaceAll("###area###", area)
						.replaceAll(
								"###prePage###",
								(i / PageUtils.DEFAULT_PAGE_SIZE) == 0 ? "1"
										: String.valueOf(i
												/ PageUtils.DEFAULT_PAGE_SIZE))
						.replaceAll(
								"###nextPage###",
								((i / PageUtils.DEFAULT_PAGE_SIZE) + 1)
										* PageUtils.DEFAULT_PAGE_SIZE > l
										.size() ? String.valueOf(i
										/ PageUtils.DEFAULT_PAGE_SIZE + 1)
										: String.valueOf(i
												/ PageUtils.DEFAULT_PAGE_SIZE
												+ 2))
						.replaceAll(
								"###totalPages###",
								String.valueOf(l.size()
										/ PageUtils.DEFAULT_PAGE_SIZE + 1))
						.replaceAll(
								"###pageNo###",
								String.valueOf(i / PageUtils.DEFAULT_PAGE_SIZE
										+ 1));
				File file = new File(servletContext.getRealPath("/")
						+ "/statichtml/recruitment-detail-entry-"
						+ ((i / PageUtils.DEFAULT_PAGE_SIZE) + 1) + ".html");
				if (!file.exists()) {
					file.getParentFile().mkdirs();
					file.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(file);
				OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
				PrintWriter outFile = new PrintWriter(osw);
				outFile.write(strs);// 写入
				osw.close();
				fos.close(); // 关闭资源
				// 重置
				strs = sbf.toString();
				area = "";
			}
			area += replaceLine
					.replaceAll("###year###", l.get(i).getYear())
					.replaceAll("###provincekey###", l.get(i).getProvince())
					.replaceAll("###typekey###", l.get(i).getType())
					.replaceAll("###provincevalue###",
							provincesmap.get(l.get(i).getProvince()))
					.replaceAll("###typevalue###",
							typemap.get(l.get(i).getType()))
					.replaceAll("###inputTime###", l.get(i).getInputTime());

		}
		strs = strs
				.replaceAll("###area###", area)
				.replaceAll(
						"###prePage###",
						(i / PageUtils.DEFAULT_PAGE_SIZE) == 0 ? "1" : String
								.valueOf(i / PageUtils.DEFAULT_PAGE_SIZE))
				.replaceAll(
						"###nextPage###",
						((i / PageUtils.DEFAULT_PAGE_SIZE) + 1)
								* PageUtils.DEFAULT_PAGE_SIZE > l.size() ? String
								.valueOf(i / PageUtils.DEFAULT_PAGE_SIZE + 1)
								: String.valueOf(i
										/ PageUtils.DEFAULT_PAGE_SIZE + 2))
				.replaceAll(
						"###totalPages###",
						String.valueOf(l.size() / PageUtils.DEFAULT_PAGE_SIZE
								+ 1))
				.replaceAll("###pageNo###",
						String.valueOf(i / PageUtils.DEFAULT_PAGE_SIZE + 1));
		File file = new File(servletContext.getRealPath("/")
				+ "/statichtml/recruitment-detail-entry-"
				+ ((i / PageUtils.DEFAULT_PAGE_SIZE) + 1) + ".html");
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		PrintWriter outFile = new PrintWriter(osw);
		outFile.write(strs);// 写入
		osw.close();
		fos.close(); // 关闭资源

	}

	@Autowired
	public void setRecruitmentDetailDao(
			RecruitmentDetailDao recruitmentDetailDao) {
		this.recruitmentDetailDao = recruitmentDetailDao;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Autowired
	public void setArrayUtils(ArrayUtils arrayUtils) {
		this.arrayUtils = arrayUtils;
	}

	@Autowired
	public void setProvinceScoreDao(ProvinceScoreDao provinceScoreDao) {
		this.provinceScoreDao = provinceScoreDao;
	}

}
